package org.tong;

import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.env.AbstractEnvironment;
import org.springframework.core.env.EnumerablePropertySource;
import org.springframework.core.env.Environment;
import org.springframework.core.env.PropertySource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@Controller
@SpringBootApplication
@EnableApolloConfig
public class FirstController {

    @Autowired
    private Environment environment;

    @ResponseBody
    @RequestMapping("/")
    public String index(@RequestParam(name = "key", required = false) String key) {
        if (key == null) {
            return "key not set";
        } else {
            return environment.getProperty(key, "notExist");
        }
    }

    @RequestMapping("/all")
    public String all(Model model) {
        List<ConfigBean> configBeans = initConfigBeans();
        model.addAttribute("configBeans", configBeans);
        return "config.html";
    }


    private List<ConfigBean> initConfigBeans() {
        List<ConfigBean> configBeanList = new ArrayList<>();
        for (PropertySource<?> propertySource : ((AbstractEnvironment) environment).getPropertySources()) {
            if (propertySource instanceof EnumerablePropertySource) {
                ConfigBean configBean = new ConfigBean();
                configBean.setName(propertySource.getName());
                configBean.setProps(new ArrayList<>());
                for (String propertyName : ((EnumerablePropertySource) propertySource).getPropertyNames()) {
                    configBean.getProps().add(new ConfigBean.Prop(propertyName, environment.getProperty(propertyName)));
                }
                configBeanList.add(configBean);
            }
        }
        return configBeanList;
    }

    public static void main(String[] args) {
        SpringApplication.run(FirstController.class, args);
    }
}
